/**
 * @file key_apn.c
 * @brief 
 * @author  ()
 * @version 1.0
 * @date 2024-11-04
 * @ingroup flash
 * @copyright Copyright (C) 2019 Queclink Wireless Solutions (ShenZhen) Co., Ltd. All Rights Reserved.
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2024-11-04 <td>1.0     <td>     <td>内容
 * </table>
 */
#include "global.h"

#define LOG_TAG   "PARM"
#include "easylog/elog.h"

#include "key_params.h"
#include "../protocol_params/protocol_params.h"



/*********************************** KeyParam [APN] *****************************************/
/**
 * @brief APN存储结构
 */
typedef struct
{
    apn_param_t apn;
    uint16_t crc;
} apn_key_params_t;


/*
 * @brief	   加载SN备份参数，仅在参数掉了以后才会调用这个函数
 * @return 	   执行结果，0表示成功，非0表示失败
 * @attenttion 如果首扇区未存储,并不保证能加载成功
 **/
int8_t load_apn_key_params(apn_param_t *apn, ssize_t apn_len)
{
    apn_key_params_t temp;

    if(apn_len != sizeof(apn_param_t))
        return -EIO;

    if (!load_key_params(DIRECT_APN_OFFSET, (unsigned char *)&temp, sizeof(temp),
                         offsetof(apn_key_params_t, crc)))
    {
        log_e("load apn failed!\r\n");
        return 1;
    }

    memcpy(apn, &temp.apn, sizeof(apn_param_t));


    // 同步至配置参数
    if (!(config_set(CONFIG_ID_APN, &temp.apn)))
    {
        log_e("save apn to config failed!\r\n");
        return 1;
    }

    return 0;
}

/*
 * @brief	   同步SN主参数至备份域
 *             注册后，设备可以调用config_update_with_callback进行参数更新，
 *             同时会调用回调sync_sn_params
 * @return 	   none
 * @attenttion
 **/
static void sync_apn_params(const void *new, const void *old)
{
    // apn_key_params_t key;

    // memset(&key, 0, sizeof(key));
    // memcpy(&key.apn, (char *)new, sizeof(apn_param_t));
    // save_key_params(DIRECT_APN_OFFSET, (unsigned char *)&key, sizeof(key),
    //                 offsetof(apn_key_params_t, crc));
}config_update_callback_register(CONFIG_ID_APN, sync_apn_params);

